var _TouchEvent = require('event/touchevent.js');

var DELE_NONE = -1;
var DELE_HORIZONTAL = 0;
var DELE_VERTICAL = 1;

var _ButtonIds = require('event/buttonid.js');
var BUTTON_DOWN = _ButtonIds.BUTTON_DOWN;
var BUTTON_UP = _ButtonIds.BUTTON_UP;
var BUTTON_MOVE = _ButtonIds.BUTTON_MOVE;
var BUTTON_CANCEL = _ButtonIds.BUTTON_CANCEL;

var MIN_MOVE = 0;

// ==========================
// Delegates
// ==========================
function Delegates(horizontal, vertical) {
    this.mDelegates = [horizontal, vertical];

    this.mActive = DELE_NONE;
    this.mEnableVertal = false;
    this.mEvent = new _TouchEvent();
    this.mSelDown = false;
}
Delegates.prototype.pieceChange = function (piece) {
    this.setEnableVertal(piece.getId() != 'record');
};
Delegates.prototype.selEnd = function (event) {
    this.selMove(event);
};
Delegates.prototype.selMove = function (event) {
    if (!this.mSelDown) {
        this.selBegin(event);
    }

    var disx = event.vector[0] - this.mEvent.vector[0];
    var disy = event.vector[1] - this.mEvent.vector[1];
    var adisx = Math.abs(disx);
    var adisy = Math.abs(disy);
    if (adisx < MIN_MOVE && adisy < MIN_MOVE) {
        return;
    }
    if (adisx > adisy) {
        this.mActive = DELE_HORIZONTAL;
    } else {
        this.mActive = DELE_VERTICAL;
    }

    event.cloneTo(this.mEvent);
    this.mEvent.setStateDown();
    this.mDelegates[this.mActive].onTouch(this.mEvent);
};
Delegates.prototype.selBegin = function (event) {
    event.cloneTo(this.mEvent);
    this.mSelDown = true;
};
Delegates.prototype.selectChild = function (event) {
    switch (event.state) {
        case BUTTON_DOWN:
            this.selBegin(event);
            break;
        case BUTTON_MOVE:
            this.selMove(event);
            break;
        case BUTTON_UP:
            this.selEnd(event);
            break;
    }
};
Delegates.prototype.setEnableVertal = function (enable) {
    this.mEnableVertal = enable;
    if (!enable) {
        this.mActive = -1;
        this.mSelDown = false;
    }
};
Delegates.prototype.onTouch = function (event) {
    // select vertical or horizontal
    if (this.mActive == -1) {
        if (this.mEnableVertal) {
            this.selectChild(event);
            if (this.mActive == -1) {
                return false;
            }
        } else {
            this.mActive = 0;
        }
    }

    var res = this.mDelegates[this.mActive].onTouch(event);
    // reset current delegate on button up
    if (event.state == BUTTON_UP) {
        this.mActive = -1;
    }

    return res;
};

module.exports = Delegates;